<template>
	<Teleport to="body">
		<transition
			appear
			name="custom-classes-transition"
			enter-active-class="animate__animated animate__faster animate__fadeIn"
			leave-active-class="animate__animated animate__faster animate__fadeOut"
		>
			<div class="tool-popup" :style="{ left: popupLeft, top: popupTop }" v-if="visible" ref="popupRef">
				<div class="tool-popup-header">
					<slot name="title"
						><div class="title">{{ Title }}</div>
					</slot>
					<div class="right-icon">
						<slot name="rightIcon"> </slot>
					</div>
				</div>
				<div class="content">
					<component :is="component" v-if="component" v-bind="componentProps"></component>
					<slot v-else></slot>
				</div>
			</div>
		</transition>
	</Teleport>
</template>
<script lang="ts">
	export default {
		name: 'popup',
	}
</script>
<script lang="ts" setup>
	import { computed, onMounted, ref } from 'vue'
	import { PopupProps } from './interface'
	import { pxToRem } from '@/utils/common'
	import { useDrag } from '@/hooks/useDrag'
	import { px2remOptions, ratio } from '@/utils/pxtorem'

	const props = withDefaults(defineProps<PopupProps>(), {
		drag: false,
	})
	const visible = defineModel('visible', { required: true })
	const emits = defineEmits(['getContentRef'])
	const { Left, Top, init } = useDrag({ left: props.left, top: props.top })
	const popupLeft = computed(() => {
		const baseHeight = px2remOptions.rootValue * ratio
		const currHeight = window.innerHeight
		if (baseHeight % currHeight == 0 || currHeight % baseHeight == 0) {
			return pxToRem(Left.value)
		}
		return Left.value + 'px'
	})
	const popupTop = computed(() => {
		const baseHeight = px2remOptions.rootValue * ratio
		const currHeight = window.innerHeight
		if (baseHeight % currHeight == 0 || currHeight % baseHeight == 0) {
			return pxToRem(Top.value)
		}
		return Top.value + 'px'
	})
	const Title = computed(() => props.title)
	const popupRef = ref()
	onMounted(() => {
		if (popupRef.value && props.drag) {
			init(popupRef.value)
		}
	})
</script>
<style lang="scss" scoped>
	.tool-popup {
		position: absolute;
		z-index: 30;
		// border-radius: 5px;
		user-select: none;
	}

	.tool-popup-header {
		position: relative;
		background-image: url('@/assets/images/global/popup-title.png');
		background-size: 100% 100%;
		box-sizing: border-box;
		height: 40px;
		line-height: 40px;
		border-top-left-radius: 5px;
		padding-left: 10px;
		padding-right: 10px;
		font-size: 16px;
		font-family: 'OPPO';
		font-weight: 400;
		display: flex;
		color: #fff;
		cursor: pointer;
		justify-content: space-between;
		.title {
			font-size: 20px;
		}
		.right-icon {
			display: flex;
			align-items: center;
			img {
				width: 30px;
				height: 30px;
			}
		}
	}

	.content {
		width: 100%;
		overflow-y: auto;
		max-height: 600px;
		color: #fff;
		background-image: url('@/assets/images/global/popup-bg.png');
		background-size: 100% 100%;
	}
</style>
